package com.kgc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.kgc.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kgc.pojo.User;
import com.kgc.service.UserService;
import com.kgc.utils.Constants;

@Controller
public class LoginController {

	@Autowired
	private UserService userService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RedisUtil redisUtil;
	/**
	 * 退出
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/logout.htm",method=RequestMethod.POST)
	@ResponseBody
	public Object logout(HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			session.invalidate();
			redisUtil.del(Constants.USER_LOGIN_KEY);
			map.put("result", true);
			map.put("message", "退出成功");
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("message", "退出访问异常："+e);
		}

		return map;
	}

	/**
	 * 登录
	 * @param session
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/login.htm")
	@ResponseBody
	public Object login(HttpSession session,String name, String password){
		Map<String, Object> map = new HashMap<String, Object>();
		System.out.println("hello");
		/**
		 * success-请求是否成功
		 * result-登录是否成功
		 * message-提示信息
		 */
		try {
			//模拟网络延迟
			//Thread.sleep(1000*3);
			User user = userService.getUserByLogin(name, password);
			if(user != null){//登录成功
				session.setAttribute(Constants.USER_LOGIN_KEY, user);
				/*redisTemplate.opsForValue().set(Constants.USER_LOGIN_KEY,user);*/
				redisUtil.set(Constants.USER_LOGIN_KEY, user);
				map.put("result", true);
				System.out.println("登录成功,success,");
				map.put("message", "登录成功,success,");
			}else{//登录失败
				map.put("result", false);
				map.put("message", "用户名或密码输入错误");
			}
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("message", "登录接口访问异常:"+e);
		}

		return map;
	}
}
